package com.gdut.simple.presenter;

import com.gdut.simple.R;
import com.gdut.simple.basic.BasicApplication;
import com.gdut.simple.common.NetworkUtils;
import com.gdut.simple.common.RequestCallback;
import com.gdut.simple.contract.NewsContract;
import com.gdut.simple.data.entity.News;
import com.gdut.simple.model.INewsModel;
import com.gdut.simple.model.impl.NewsModelImpl;

import java.util.List;

public class NewsPresenter implements NewsContract.Presenter {


    private NewsContract.View mNewsView;
    private INewsModel mNewsModel;

    public NewsPresenter(NewsContract.View view) {
        this.mNewsView = view;
        mNewsModel = new NewsModelImpl();
        mNewsView.setPresenter(this);
    }

    @Override
    public void refresh() {
        mNewsView.showRefreshProgress();
        if (!NetworkUtils.isConnected(BasicApplication.getApplication())) {
            mNewsView.hideRefreshProgress();
            mNewsView.showMessage(BasicApplication.getApplication().getResources().getString(R.string.msg_error_net));
            return;
        }
        mNewsModel.refresh(mNewsView.getType(), 10, new RequestCallback<List<News>>() {
            @Override
            public void onSuccess(List<News> list) {
                mNewsView.getItemList().clear();
                mNewsView.getItemList().addAll(list);
                mNewsView.refreshList();
                mNewsView.reset();
                mNewsView.hideRefreshProgress();
            }

            @Override
            public void onFailure(String message) {
                mNewsView.hideRefreshProgress();
                mNewsView.showMessage(BasicApplication.getApplication().getResources().getString(R.string.msg_refresh_fail));
            }
        });
    }

    @Override
    public void loadMore(int page) {
        if (!NetworkUtils.isConnected(BasicApplication.getApplication())) {
            mNewsView.showMessage(BasicApplication.getApplication().getResources().getString(R.string.msg_error_net));
            return;
        }
        mNewsModel.loadMore(mNewsView.getType(), 10, page, new RequestCallback<List<News>>() {
            @Override
            public void onSuccess(List<News> list) {
                if (list == null || list.size() == 0) {
                    return;
                }
                mNewsView.getItemList().addAll(list);
                mNewsView.refreshList();
            }

            @Override
            public void onFailure(String message) {
                mNewsView.showMessage(BasicApplication.getApplication().getResources().getString(R.string.msg_load_fail));
            }
        });
    }

}
